﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using Wamm.ApplicationExceptions;
using WAMM.Domain.Services.Person;
using WAMM.Domain.Services.Person.Parameters;
using WAMM.Domain.Services.Photo;
using WAMM.Domain.Services.Photo.Parameters;
using WAMM.Domain.Services.ViewModels;
using WAMM.WebUI.Infrastructure;
using WAMM.WebUI.Models;
using System.Web;

namespace WAMM.WebUI.Controllers {
    public partial class PersonController : Controller {

        private readonly IPersonService _personService;
        private readonly IPhotoService _photoService;

        public PersonController(IPersonService personService, IPhotoService photoService) {
            _personService = personService;
            _photoService = photoService;
        }

        //
        // GET: /Person/

        public virtual ActionResult Index() {

            var svcRequest = new GetAllPeopleRequest();
            svcRequest.IncludedDeleted = false;

            var svcResponse = _personService.GetAllPeople(svcRequest);

            var model = Mapper.Map<IList<PersonServiceModel>, IList<WAMM.WebUI.Models.PersonWebUIModel>>(svcResponse.People);

            return View(model);
        }

        //
        // GET: /Person/Details/5

        public virtual ActionResult Details(int id) {
            var personWebUIModel = GetModelForId(id);
            return View(personWebUIModel);
        }

        //
        // GET: /Person/Create

        public virtual ActionResult Create() {
            var personWebUIModel = new PersonWebUIModel();
            return View(personWebUIModel);
        }

        //
        // POST: /Person/Create

        [HttpPost]
        public virtual ActionResult Create(Models.PersonWebUIModel personWebUIModel) {
            try {
                if (ModelState.IsValid) {
                    var svcRequest = new CreatePersonRequest();
                    svcRequest.Person = Mapper.Map<WAMM.WebUI.Models.PersonWebUIModel, PersonServiceModel>(personWebUIModel);

                    _personService.CreatePerson(svcRequest);

                }
            }
            catch (RulesException ex) {
                ex.CopyTo(ModelState);
            }

            if (ModelState.IsValid) {
                return RedirectToAction(MVC.Person.Index());
            }
            else {
                return View(personWebUIModel);
            }
        }

        //
        // GET: /Person/Edit/5

        public virtual ActionResult Edit(int id) {
            var personWebUIModel = GetModelForId(id);
            return View(personWebUIModel);
        }

        //
        // POST: /Person/Edit/5

        [HttpPost]
        public virtual ActionResult Edit(int id, PersonWebUIModel personWebUIModel) {
            try {
                if (ModelState.IsValid) {
                    var svcRequest = new UpdatePersonRequest();
                    svcRequest.Person = Mapper.Map<WAMM.WebUI.Models.PersonWebUIModel, PersonServiceModel>(personWebUIModel);

                    _personService.UpdatePerson(svcRequest);
                }
            }
            catch (RulesException ex) {
                ex.CopyTo(ModelState);
            }
            catch (DataUpdatedBySomeoneElseException exUpdatedBySomeoneElse) {
                ModelState.AddModelError(string.Empty, Constants.DATA_UPDATED_BY_SOMEONE_ELSE);
                personWebUIModel = GetModelForId(id);
                System.Diagnostics.Trace.WriteLine(exUpdatedBySomeoneElse);
            }

            if (ModelState.IsValid) {
                return RedirectToAction(MVC.Person.Index());
            }
            else {
                return View(personWebUIModel);
            }
        }

        //
        // GET: /Person/Delete/5

        public virtual ActionResult Delete(int id) {
            var personWebUIModel = GetModelForId(id);

            return View(personWebUIModel);
        }

        //
        // POST: /Person/Delete/5

        [HttpPost]
        public virtual ActionResult Delete(int id, PersonWebUIModel personWebUIModel) {
            try {
                var svcRequest = new DeletePersonRequest { Id = id };

                _personService.DeletePerson(svcRequest);

                return RedirectToAction(MVC.Person.Index());
            }
            catch {
                return View();
            }
        }

        public virtual FileUploadJsonResult UploadPicture(HttpPostedFileBase file, int Id) {

            if (file.ContentLength > 0) {
                var pictureBytes = new byte[file.ContentLength];
                file.InputStream.Read(pictureBytes, 0, pictureBytes.Length);
                var svcRequest = new UpdatePictureRequest() { PersonId = Id, PictureBytes = pictureBytes};
                _personService.UpdatePicture(svcRequest);
            }
            return new FileUploadJsonResult {Data = new {id = Id}};
        }

        public virtual ActionResult ShowPhoto(int id, string sizeType) {
            var photoSizeType = ValidatePhotoSizeType(sizeType);
            var svcRequest = new GetPersonPhotoRequest
                                      {
                                          Id = id,
                                          SizeType = photoSizeType.ToString()
                                      };
            var svcResponse = _personService.GetPersonPhoto(svcRequest);

            var result = new ImageResult(svcResponse.Photo, "imgage/jpeg");
            return result;
        }

        private static PhotoWebUIModel.Size ValidatePhotoSizeType(string sizeType)
        {
            PhotoWebUIModel.Size photoSizeType;
            if (!Enum.TryParse(sizeType, true, out photoSizeType))
            {
                throw new ArgumentException(String.Format("Unknow value for sizeType={0}", sizeType));
            }
            return photoSizeType;
        }

        private PersonWebUIModel GetModelForId(int id) {
            var svcRequest = new GetPersonRequest { Id = id };

            var svcResponse = _personService.GetPerson(svcRequest);
            var webUiModel = Mapper.Map<PersonServiceModel, WAMM.WebUI.Models.PersonWebUIModel>(svcResponse.Person);
            webUiModel.PictureUrl = string.Format("/Person/ShowPhoto/{0}", webUiModel.Id);

            return webUiModel;
        }

    }
}
